package jd.se.home;

import jd.se.common.CurrentUser;
import jd.se.common.Result;
import jd.se.common.Utils;
import jd.se.login.LoginService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.UUID;

/**
 * @author SunJiahao
 * @date 2021-05-22 16:15
 */
@MultipartConfig //此注解表示可以接收上传文件
@WebServlet({
        "/current-user",
        "/avatar"
})
public class HomeAPI extends HttpServlet {
    @Override
    public void init() throws ServletException {
        File dir = new File(CurrentUser.AVATAR_DIR);//表示文件或目录的路径
        if(!dir.exists()){//目录不存在则创建
            dir.mkdirs();

        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HomeService service = new HomeService();

        request.setCharacterEncoding("UTF-8");//设置请求编码，防止获取请求信息中文乱码
        String path = request.getServletPath();//获取请求路径

        if("/avatar".equals(path)){
            Part part = request.getPart("avatar");

            InputStream in = part.getInputStream();

            String name = UUID.randomUUID().toString();//获得通过uuid算法得到的不重复的字符串
            String submitedFilename = part.getSubmittedFileName();//原始文件名
            String suffix = submitedFilename.substring(submitedFilename.lastIndexOf("."));
            String filename = name+suffix;
            OutputStream out = new FileOutputStream(CurrentUser.AVATAR_DIR+"/"+filename);

            byte[] b = new byte[10240];//容量为10240字节的缓存区
            int len = -1;//从输入流读取并放入缓存区的数据量

            while((len=in.read(b))!=-1){
                out.write(b,0,len);
            }
            out.flush();
            out.close();
            in.close();

            CurrentUser currentUser = (CurrentUser)request.getSession().getAttribute(CurrentUser.SESSION_ATTR_NAME);
            service.setAvatar(currentUser,filename);

            Utils.outResult(response, Result.success());
        }
        if("/exit".equals(path)){
            request.getSession().removeAttribute(CurrentUser.SESSION_ATTR_NAME);
            Utils.outResult(response, Result.success());
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        HomeService service = new HomeService();
        if("/current-user".equals(path)){
            CurrentUser currentUser = (CurrentUser)request.getSession().getAttribute(CurrentUser.SESSION_ATTR_NAME);
            System.out.println("currentUser->"+currentUser);
            service.loadCurrentUser(currentUser);//加载完整的用户信息
            Utils.outResult(response, Result.success(currentUser));
        }
        if("/avatar".equals(path)){
            //从请求参数中通过参数名称filename获取文件名称
            String filename = request.getParameter("filename");
            //读取文件的输入流
            InputStream in = new FileInputStream(CurrentUser.AVATAR_DIR+"/"+filename);
            //将文件信息输出到浏览器的输出流
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[10240];//容量为10240字节的缓存区
            int len = -1;//从输入流读取并放入缓存区的数据量
            while((len=in.read(b)) != -1){
                out.write(b,0,len);
            }
            out.flush();
            out.close();
            in.close();
        }
    }
}
